package com.woniuxy.charin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.charin.model.entity.Permission;
import com.woniuxy.charin.service.PermissionService;
import com.woniuxy.charin.mapper.PermissionMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author KOO
* @description 针对表【permission】的数据库操作Service实现
* @createDate 2024-12-26 16:45:32
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
    implements PermissionService {

    /**
     * 获取权限树
     *
     * @return
     */
    @Override
    public List<Permission> getPermissions() {
        List<Permission> allPermissions = this.list();
        List<Permission> perTree = allPermissions.stream()
                .filter(p -> p.getLevel() == 1)
                .collect(Collectors.toList());
        setChildPermissions(perTree, allPermissions);
        return perTree;
    }

    @Override
    public List<Integer> getPermissionIdByRole(Integer roleId) {
        List<Integer> allPermissionId = baseMapper.getPermissionIdByRole(roleId);
        return allPermissionId;
    }

    @SneakyThrows
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void assignPermission(Long roleId, List<Integer> permissionIds) {
            baseMapper.deleteByRole(roleId);
            baseMapper.batchInsert(roleId,permissionIds);
    }


    //设置子权限
    private void setChildPermissions(List<Permission> parentPermissions,
                                     List<Permission> allPermissions) {
        for (Permission parent : parentPermissions) {
            List<Permission> children = allPermissions.stream()
                    .filter(p -> p.getParentId() == parent.getId())
                    .collect(Collectors.toList());
            if (children == null || children.size() == 0) {
                continue;
            }
            parent.setChildren(children);
            setChildPermissions(children, allPermissions);
        }
    }
}




